//
// Created by lei on 7/12/23.
//
#include <com_SSMp4v2_SSMp4v2.h>
#include "Mp4Muxer.h"
#include "Mp4Muxer.c"
#import <stdlib.h>
#include <jni.h>

uint8_t* jbyteArrayToUint8(JNIEnv* env, jbyteArray arr) {
    // 获取字节数组的长度
    jsize len = (*env)->GetArrayLength(env, arr);
    // 分配内存来存储字节数组
    uint8_t* bytes = (uint8_t*)malloc(len);
    // 将字节数组的每个元素复制到新分配的内存中
    (*env)->GetByteArrayRegion(env, arr, 0, len, bytes);
    return bytes;
}

JNIEXPORT jint
JNICALL
Java_com_SSMp4v2_SSMp4v2_fileCreate(JNIEnv *env, jclass clazz, jstring p_file_name, jint width,
                                       jint height, jint frame_rate) {
    // TODO: implement fileCreate()
    const char* filePath = p_file_name ? (*env)->GetStringUTFChars(env, p_file_name, 0) : NULL;
    LOGE("Java_com_SSMp4v2_SSMp4v2_fileCreate fname=%s\n", filePath);
    if (filePath == NULL) {
        return -1;
    }
    int result = fileCreate(filePath, width, height, frame_rate);
    (*env)->ReleaseStringUTFChars(env, p_file_name, filePath);
    return result;
}

JNIEXPORT jint
JNICALL
Java_com_SSMp4v2_SSMp4v2_fileWrite(JNIEnv *env, jclass clazz, jint frame_type,
                                      jbyteArray pframe_buf, jint frame_len) {
    // TODO: implement fileWrite()
    return fileWrite(frame_type, jbyteArrayToUint8(env,pframe_buf), frame_len);
}

JNIEXPORT jint
JNICALL
Java_com_SSMp4v2_SSMp4v2_fileClose(JNIEnv *env, jclass clazz) {
    // TODO: implement fileClose()
    return fileClose();
}


